import flash.net.FileReference;

var job2commit:Number;
var uuid2commit:String;
var resourceUploadUrl:String;
var resourceDownloadUrl:String;
var uploadQueue:Array;
var uploadFlag:Boolean;
var subtype:String;

function initCoverUpload()
{
	job2commit=null;
	uuid2commit=null;
	setResourceServerUrl();
	uploadQueue=new Array();
	uploadFlag=false;
}

function disposeCoverUpload()
{
	job2commit=null;
	uuid2commit=null;
	uploadQueue=new Array();
	uploadFlag=false;
	subtype=null;
}

function setUuid2Commit(param:String)
{
	uuid2commit=param;
}

function getUuid2Commit():String
{
	return uuid2commit;
}

function setResourceServerUrl()
{
	resourceUploadUrl=Packages.system.mlf.GateKeeper.accessSystemConfig("httpRequest")+"/upload";
	resourceDownloadUrl=Packages.system.mlf.GateKeeper.accessSystemConfig("httpRequest")+"/download";
}

function getResourceUploadUrl():String
{
	return resourceUploadUrl;
}

function getResourceDownloadUrl():String
{
	return resourceDownloadUrl;
}

function addFileToUploadQueue(file:Object):Boolean {
	for (var i:Number = 0; i<uploadQueue.length; i++) {
		if (uploadQueue[i].item.name == file.item.name) {
			return false;
		}
	}
	uploadQueue.push(file);
	return true;
}

function delFileFromUploadQueue(jobId:Number):Object {
	var file:Object = new Object();
	for (var i:Number = 0; i<uploadQueue.length; i++) {
		file = uploadQueue[i];
		if (uploadQueue[i].jobId == jobId) {
			uploadQueue.splice(i, 1);
			return file;
		}
	}
	return null;
}

function openFileDialog()
{
	uploadFlag=true;
	fileRef=new FileReference();
	var listener:Object = new Object();
	listener.owner = this;
	listener.onSelect = function(file:FileReference) {
		var obj:Object = new Object();
		obj.item = file;
		obj.date = getTimestamp();
		var offset:Number = Math.floor(Math.random()*1000000)+1000000;
		obj.jobId = offset+obj.date;
		obj.stat = "waiting";
		if (addFileToUploadQueue(obj)) {
			file.addListener(this);
			if (obj.item.name != null && obj.item.name != "") {
				traceItem(obj);
			}
			job2Commit=obj.jobId;

			var uuid:String;
			var item=new Object();
			item.type="generateUuid";
			item.param=new Object();
			item.result=new Object();
			item.result.owner=this;
			item.result.onResult=function(res)
			{
				Packages.log("generateUuid.onResult: "+res.returnObj, "debug");
				if (res.returnObj!=null)
				{
					obj.uuid=res.returnObj;
					this.owner.owner.uploadResource(obj);
					this.owner.owner.setUuid2Commit(res.returnObj);
				}
			}	
			Packages.services.RemotingCall.rtmpCaller(item);
		}
	};

	listener.onCancel = function(file:FileReference):Void  {
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "onCancel";
		file.removeListener(this);
		uploadFlag=false;
	};

	listener.onOpen = function(file:FileReference):Void  {
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "onOpen";
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
	};

	listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void  {
		var progress:String = Math.floor(bytesLoaded/bytesTotal*100)+"%";
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = progress;
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
	};

	listener.onComplete = function(file:FileReference):Void  {
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "completed";
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
		file.removeListener(listener);
		uploadFlag=false;

		this.owner.loadCover2Clip("clipCover", uuid2commit);
		//commitResource(uuid2Commit, bookName.htmlText, bookAuthor.htmlText);
	};

	listener.onHTTPError = function(file:FileReference, httpError:Number):Void  {
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "httpError";
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
		file.removeListener(listener);
	};

	listener.onIOError = function(file:FileReference):Void  {
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "IoError";
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
		file.removeListener(listener);
	};

	listener.onSecurityError = function(file:FileReference, errorString:String):Void  {
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "securityError";
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
		file.removeListener(listener);
	};

	fileRef.addListener(listener);
	var fileTypes:Array=[{description:"Image", extension:"*.jpg;*.gif;*.png"}];
	fileRef.browse(fileTypes);
}

function uploadResource(element:Object)
{
	var jobId:String = element.jobId;
	var file:FileReference = element.item;
	var stat:String = element.stat;
	if (file == undefined) {
		return;
	}

	if (file.size>900000000) {
		file.removeListener();
		return;
	}

	if (stat != "waiting") {
		return;
	}

	element.stat = "uploading";
	var fileName:Array = file.name.split(file.type);
	element.fileName = fileName[0];
	Packages.log("file name:"+fileName[0]+" file type:"+file.type, "debug");
	if (file.type.toLowerCase()==".jpg") {
		subtype = "1";
	} else if (file.type.toLowerCase()==".gif") {
		subtype = "2";
	} else if (file.type.toLowerCase()==".png") {
		subtype = "3";
	} else {
		subtype = "-1";
	}

	var url = getResourceUploadUrl()+"?uuid="+element.uuid+"&type=3&"+"subtype="+subtype+"&sessionId="+Packages.model.Context.sessionID;
	Packages.log("uploadUrl:"+url, "debug");
	file.upload(url);
}

function traceItem(obj)
{
	Packages.log("traceItem: "+obj.stat, "debug");
	/*var file=Packages.system.mlf.GateKeeper.scanElement(this._name, "file");
	var stat=Packages.system.mlf.GateKeeper.scanElement(this._name, "stat");
	if (obj.stat!=null)
		stat.text=obj.stat;
	if (obj.item.name!=null)
		file.text=obj.item.name;
	if (obj.stat=="onOpen")
		uploadFlag=true;
	if (obj.stat=="completed")
		uploadFlag=false;*/
}

function getTimestamp():Number 
{
	var date:Date = new Date();
	var timestamp = date.getTime();
	delete date;
	return timestamp;
}

/*
function loadImageUpload(target)
{
	//Packages.system.mlf.GateKeeper.updateDynamicPortlet(target._parent, "app/vo/ChapterUpload.xml");
	//dynamicPortletArr.chapterList="chapterUpload";
}

function confirmImageUpload()
{
	if (uploadFlag) return;
	
	var number=Packages.system.mlf.GateKeeper.scanElement(this._name, "number");
	var name=Packages.system.mlf.GateKeeper.scanElement(this._name, "name");
	var abstract=Packages.system.mlf.GateKeeper.scanElement(this._name, "abstract");
	var file=Packages.system.mlf.GateKeeper.scanElement(this._name, "file");
	if (file.text==null) return;

	var obj:Object=new Object();
	obj.memberId=Packages.model.UserProfile.data.memberId+"";
	obj.bookId=Packages.model.Context.address.id+"";
	obj.number=number.text;
	obj.name=name.text;
	obj.abstract=abstract.text;
	obj.uuid=getUuid2Commit();
	var data:Object=new Object();
	// data.path=target._parent;
	data.name="BookSpecial";
	data.container="chapterListContainer";
	data.oper="chapterCreate";
	data.uri="app/content/bookPage/BookSpecial.xml";
	
	data.returnPath="loadChapterList";
	data.dynamicPortlet=dynamicPortletArr.chapterList;

	dynamicPortletArr.chapterList="commonRemotingResult";

	Packages.modula.RequestCommand.request("REMOTING", "chapterCreate", obj, Packages.model.vo.CommonRemotingResultView, displayMode.chapterList, this, data);
}

function onImageUploadInit()
{
	var evtTargetArr:Array=new Array();
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "uploadFileSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "uploadConfirmSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "uploadReturnSpot"));
	Packages.system.events.StateFulButtonEvent.initialize(evtTargetArr);
}
*/
